﻿// Copyright (c) 2014 Jonathan Magnan (http://jonathanmagnan.com/).
// All rights reserved (http://zzzproject.com/sqlbulkcopy-extensions/).
// Licensed under MIT License (MIT) (https://zsqlbulkcopy.codeplex.com/license/).
using System.Reflection;

namespace Z.Net.Extensions
{
    internal partial class SqlBulkOperation
    {
        /// <summary>
        ///     Ensures a transaction is set if none is specified.
        /// </summary>
        public void EnsureTransactionIsSet()
        {
            if (SqlTransaction == null)
            {
                SqlTransaction = SqlConnection.BeginTransaction();
// ReSharper disable PossibleNullReferenceException
                SqlBulkCopy.GetType().GetField("_externalTransaction", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(SqlBulkCopy, SqlTransaction);
// ReSharper restore PossibleNullReferenceException
                IsInternalTransaction = true;
            }
        }
    }
}